package com.prime;

import com.cache.Cache;
import com.cache.PrimeStorage;
import com.cache.Storage;

import java.util.concurrent.*;
import java.util.function.Function;

public class RightPrimeChecker implements CanCheckIfPrime {

	private static final WrongIfPrimeChecker delegate = new WrongIfPrimeChecker();
	private static final ConcurrentHashMap<Integer, Future<Boolean>> isPrimeCache = new ConcurrentHashMap<Integer, Future<Boolean>>();

	private static final Cache cache = new Cache(new PrimeStorage(delegate), 100000, 10000);
	
	/**
	 * Thread safe!
	 * */
	@Override
	public boolean isPrime(int number) {
		//System.out.println("Will be written using " + delegate);

		// TODO: write as homework

		/*Future<Boolean> f = isPrimeCache.get(number);

		if (f == null) {
			FutureTask<Boolean> ft = new FutureTask<Boolean>(() -> {
				return delegate.isPrime(number);
			});

			f = isPrimeCache.putIfAbsent(number, ft);
			if (f == null) {
				f = ft;
				ft.run();
			}
		}

		try {
			return f.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}*/

		return (Boolean) cache.get(new Long(number));

		//return false;
	}
	
}
